package com.kob.backend.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.kob.backend.consumer.utils.Game;
import com.kob.backend.consumer.utils.JwtAuthentication;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾,token是令牌
public class WebSocketServer {//每来一个需要连接的client，就new一个该类的实例对象，所有和链接相关的信息都存到这个类里面

    //静态变量需要用类名来访问
    //加上static对于所有对象都可见，相当于一个全局变量，没有static的话就是每个对象独一份,所有连接对象都访问同一个哈希表
    final public static ConcurrentHashMap<Integer,WebSocketServer> users=new ConcurrentHashMap<>();//把userid映射到WebSocketServer对象中
    private User user;
    private Session session=null;//WebSocket里面一个包（api），user信息存到session里面

    public static UserMapper userMapper;//WebSocket特殊，需要加static
    public static RecordMapper recordMapper;
    private static BotMapper botMapper;
    public static RestTemplate restTemplate;//用于发送请求
    public Game game=null;
    private final static String addPlayerUrl="http://127.0.0.1:3001/player/add/";
    private final static String removePlayerurl="http://127.0.0.1:3001/player/remove/";

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper=userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper){
        WebSocketServer.recordMapper=recordMapper;
    }

    @Autowired
    public void setBotMapper(BotMapper botMapper){
        WebSocketServer.botMapper=botMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        WebSocketServer.restTemplate=restTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session=session;//建立连接时候需要把session存下来
        System.out.println("connected!");//建立连接成功后输出的调试信息
        Integer userId= JwtAuthentication.getUserId(token);//把userid从token中解析出来
        //根据id查数据库，查这个user是谁
        this.user=userMapper.selectById(userId);

        if(this.user!=null){
            //把查到的user存下来
            users.put(userId,this);//保存：哪个user对应哪个连接
        }else {
            this.session.close();
        }

        System.out.println(users);
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.out.println("disconnected!");//关闭连接成功后输出的调试信息
        //断开连接后要把user连接信息删掉
        if (this.user!=null){
            users.remove(this.user.getId());
        }
    }

    public static void startGame(Integer aId,Integer aBotId,Integer bId,Integer bBotId){
        User a=userMapper.selectById(aId),b=userMapper.selectById(bId);
        //取出俩bot
        Bot botA=botMapper.selectById(aBotId),botB=botMapper.selectById(bBotId);
        //创建游戏地图
        Game game=new Game(13,
                14,
                20,
                a.getId(),
                botA,
                b.getId(),
                botB
        );
        game.createMap();

        //game进程是俩玩家的，需要赋值给它们
        if(users.get(a.getId())!=null){
            users.get(a.getId()).game=game;
        }
        if(users.get(b.getId())!=null){
            users.get(b.getId()).game=game;
        }

        //进入新线程
        game.start();//另起一个线程


        //把地图相关信息封装成json
        JSONObject respGame=new JSONObject();
        //坐标
        respGame.put("a_id",game.getPlayerA().getId());
        respGame.put("a_sx",game.getPlayerA().getSx());
        respGame.put("a_sy",game.getPlayerA().getSy());
        respGame.put("b_id",game.getPlayerB().getId());
        respGame.put("b_sx",game.getPlayerB().getSx());
        respGame.put("b_sy",game.getPlayerB().getSy());
        //把地图信息一块传进来
        respGame.put("map",game.getG());

        //传送配对成功的消息
        //json对象就是一组字典/map
        JSONObject respA=new JSONObject();
        respA.put("event","start-matching");
        respA.put("opponent_username",b.getUsername());
        respA.put("opponent_photo",b.getPhoto());
        respA.put("game",respGame);
        if (users.get(a.getId())!=null){
            //从哈希表中获取a并把json传送给前端
            users.get(a.getId()).sendMessage(respA.toJSONString());
        }

        JSONObject respB=new JSONObject();
        respB.put("event","start-matching");
        respB.put("opponent_username",a.getUsername());
        respB.put("opponent_photo",a.getPhoto());
        respB.put("game",respGame);
        if (users.get(b.getId())!=null){
            users.get(b.getId()).sendMessage(respB.toJSONString());
        }
    }

    private void startMatching(Integer botId){
        System.out.println("start matching!");
        MultiValueMap<String,String> data=new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        data.add("rating",this.user.getRating().toString());
        data.add("bot_id",botId.toString());
        restTemplate.postForObject(addPlayerUrl,data,String.class);
    }

    private void stopMatching(){
        System.out.println("stop matching!");
        MultiValueMap<String,String> data=new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        restTemplate.postForObject(removePlayerurl,data,String.class);
    }

    private void move(int direction){
        //判断蛇a蛇b
        if(game.getPlayerA().getId().equals(user.getId())){
            if (game.getPlayerA().getBotId().equals(-1)){
                //是蛇a(玩家亲自控制),设置其下一步
                game.setNextStepA(direction);
            }
        } else if (game.getPlayerB().getId().equals(user.getId())) {
            if (game.getPlayerB().getBotId().equals(-1))
                game.setNextStepB(direction);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {//相当于路由
        // 从Client接收消息
        System.out.println("receive message!");//接收到信息后输出的调试信息
        //解析从前端传来的信息
        JSONObject data=JSONObject.parseObject(message);
        String event=data.getString("event");//再变回字符串
        //根据event信息确定下一步行动
        if("start-matching".equals(event)){//event为空会报异常，反写可以防止报异常
            startMatching(data.getInteger("bot_id"));//开始匹配
        } else if ("stop-matching".equals(event)) {
            stopMatching();
        } else if ("move".equals(event)) {
            move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    //辅助函数,从后端向前端（当前这个链接）发送信息，每个链接用session维护
    public void sendMessage(String message){
        synchronized (this.session){//异步通信，需要加一个锁
            try{
                this.session.getBasicRemote().sendText(message);
            }catch (IOException e){
                e.printStackTrace();//输出
            }
        }
    }
}
